//package com.pansoft.openplanet.activity;
//
//import android.app.AlertDialog;
//import android.content.DialogInterface;
//import android.content.Intent;
//import android.os.Bundle;
//import android.view.View;
//import android.widget.Button;
//import android.widget.ImageView;
//import android.widget.TextView;
//
//import com.efounder.chat.model.LogoutEvent;
//import com.efounder.constant.EnvironmentVariable;
//import com.efounder.http.EFHttpRequest;
//import com.efounder.util.FileDeleteUtil;
//import com.efounder.utils.ResStringUtil;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.pansoft.openplanet.R;
//import com.pansoft.openplanet.bean.Account;
//import com.pansoft.openplanet.constant.TalkChainConstant;
//import com.pansoft.openplanet.db.AccountDao;
//import com.pansoft.openplanet.util.EthHDWalletUtils;
//import com.pansoft.openplanet.util.TCRequestUtil;
//
//import org.bitcoinj.wallet.DeterministicSeed;
//import org.greenrobot.eventbus.EventBus;
//import org.json.JSONObject;
//import org.web3j.crypto.ECKeyPair;
//import org.web3j.crypto.Wallet;
//import org.web3j.crypto.WalletFile;
//
//import java.io.File;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.List;
//
//import io.reactivex.Observable;
//import io.reactivex.ObservableEmitter;
//import io.reactivex.ObservableOnSubscribe;
//import io.reactivex.android.schedulers.AndroidSchedulers;
//import io.reactivex.annotations.NonNull;
//import io.reactivex.disposables.Disposable;
//import io.reactivex.functions.Consumer;
//import io.reactivex.schedulers.Schedulers;
//
//import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
//
///**
// * 创建钱包确认 弃用
// * Created by will on 18-3-20.
// */
//@Deprecated
//public class CreateWalletConfirm extends TCBaseActivity implements View.OnClickListener {
//
//    private static String TAG = "CreateWalletConfirm";
//    //手机号
//    private String number;
//    //钱包名称
//    private String userName;
//    //密码
//    private String password;
//    //助记词
//    private String mnemonic;
//    //帐号
//    private String address;
//    //头像
//    private String avatar;
//    //数据库
//    private AccountDao accountDao;
//    //密钥
//    private ECKeyPair ecKeyPair;
//    private WalletFile walletFile;
//    private File keyStoreFile;
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.talk_chain_activity_create_wallet_confirm);
//
//        number = getIntent().getExtras().getString("number");
//        userName = getIntent().getExtras().getString("userName");
//        password = getIntent().getExtras().getString("password");
//        avatar = getIntent().getStringExtra("avatar");
//
//        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
//        ivBack.setOnClickListener(this);
//        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
//        tvTitle.setText(ResStringUtil.getString(R.string.create_jidi_account));
//        Button tvCreateWallet = (Button) findViewById(R.id.tv_create_wallet);
//        tvCreateWallet.setOnClickListener(this);
//
//        accountDao = new AccountDao(this);
//
//    }
//
//    @Override
//    public void onClick(View view) {
//        int id = view.getId();
//        if (id == R.id.tv_create_wallet) {
//            //创建钱包
//            generateWallet();
//        } else if (id == R.id.iv_back) {
//            finish();
//        }
//    }
//
//    private void generateWallet() {
//        ecKeyPair = null;
//        address = null;
//        walletFile = null;
//        keyStoreFile = null;
//
//        showLoading(ResStringUtil.getString(R.string.open_planet_iscreateing));
//        //keystore存放的路径
//        final String path = TalkChainConstant.getDataFilePath(this) + File.separator + number;
//        //文件夹不存在，创建文件夹
//        final File file = new File(path);
//        //清空文件夹
//        if (file != null) {
//            FileDeleteUtil.delete(file);
//        }
//            file.mkdirs();
//
//
//        Disposable disposable = Observable.create(new ObservableOnSubscribe<WalletFile>() {
//            @Override
//            public void subscribe(ObservableEmitter<WalletFile> emitter) throws Exception {
//                DeterministicSeed ds = EthHDWalletUtils.createRandomDeterministicSeed("");
//                List<String> mnemonicList = ds.getMnemonicCode();
//                StringBuffer stringBuffer = new StringBuffer();
//                for (int i = 0; i < mnemonicList.size(); i++) {
//                    stringBuffer.append(mnemonicList.get(i)).append(" ");
//                }
//                mnemonic = stringBuffer.substring(0, stringBuffer.length() - 1);
//                //生成密钥
//                ecKeyPair = EthHDWalletUtils.createECKeyPairFromSeed(ds);
//                //生成walletfile
//                walletFile = Wallet.createLight("", ecKeyPair);
//
//                //test
//
//                //生成keystore文件名称
//                SimpleDateFormat dateFormat = new SimpleDateFormat("'UTC--'yyyy-MM-dd'T'HH-mm-ss.SSS'--'");
//                String fileName = dateFormat.format(new Date()) + walletFile.getAddress() + ".json";
//                //钱包地址
//                address = "0x" + walletFile.getAddress();
//                //keystore文件
//                keyStoreFile = new File(path, fileName);
//                //保存keystore 写入文件
//                ObjectMapper objectMapper = new ObjectMapper();
//                objectMapper.writeValue(keyStoreFile, walletFile);
//                //test
//
//
//                emitter.onNext(walletFile);
//                emitter.onComplete();
//
//            }
//        }).subscribeOn(Schedulers.io())        // 在io线程生成walletfile的进行操作
//                .observeOn(AndroidSchedulers.mainThread()) // 在主线程处理walletfile保存
//                .subscribe(new Consumer<WalletFile>() {
//                    @Override
//                    public void accept(@NonNull WalletFile walletFile) throws Exception {
////                        //生成keystore文件名称
////                        SimpleDateFormat dateFormat = new SimpleDateFormat("'UTC--'yyyy-MM-dd'T'HH-mm-ss.SSS'--'");
////                        String fileName = dateFormat.format(new Date()) + walletFile.getAddress() + ".json";
//                        //钱包地址
//                        address = "0x" + walletFile.getAddress();
////                        //keystore文件
////                        keyStoreFile = new File(path, fileName);
////                        //保存keystore 写入文件
////                        ObjectMapper objectMapper = new ObjectMapper();
////                        objectMapper.writeValue(keyStoreFile, walletFile);
//                        //将公钥发送给服务器
//                        //sendRsaPublicKeyToServer(address, ecKeyPair.getPublicKey().toString());
//
//
//                        saveAccount();
//                        //显示成功对话框
//                        showSuccessAlert();
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        showFailAlert(null);
//                    }
//                });
//        addDisposable(disposable);
//    }
//
//
//    private void sendToServer(String address, String publicKey) {
//        HashMap<String, String> map = new HashMap<>();
//        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
//        map.put("ethAddress", address);
//        map.put("ethPublicKey", publicKey);
//        TCRequestUtil.postOAuthRequest(TAG, "user/updateUserEthPublicKeyAndAddress", map,
//                new TCRequestUtil.TCRequestCallback() {
//                    @Override
//                    public void onSuccess(String response) {
//                        dismissLoading();
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//
//                            if (jsonObject.has("result")
//                                    && jsonObject.getString("result")
//                                    .equals("success")) {
//                                //创建账户成功，本地持久化账户信息
//                                saveAccount();
//                                //显示成功对话框
//                                showSuccessAlert();
//                            } else {
//                                //请求服务器失败，删除本地的keystore文件
//                                if (walletFile != null) {
//                                    FileDeleteUtil.delete(keyStoreFile);
//                                }
//                                showFailAlert(null);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            dismissLoading();
//                            if (walletFile != null) {
//                                FileDeleteUtil.delete(keyStoreFile);
//                            }
//                            showFailAlert(null);
//                        }
//                    }
//
//                    @Override
//                    public void onFail(String error) {
//                        dismissLoading();
//                        if (error != null && error.equals("TokenExpireLogOut")) {
//                            EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));
//                            return;
//                        }
//                        showFailAlert(error);
//                    }
//                });
//    }
//
//    //保存到数据库
//    private void saveAccount() {
//        Account account = new Account(address, userName, avatar);
//        account.setFileName(keyStoreFile.getAbsolutePath());
//        account.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
//        accountDao.insertOrReplace(account);
//    }
//
//    @Override
//    protected void onStop() {
//        super.onStop();
//        EFHttpRequest.cancelRequest(TAG);
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        dispose();
//    }
//
//    private void showFailAlert(String message) {
//        if (message == null)
//            message = ResStringUtil.getString(R.string.open_planet_create_fail_please_retry);
//        new AlertDialog.Builder(CreateWalletConfirm.this)
//                .setTitle(R.string.common_text_hint)
//                .setMessage(message)
//                .setPositiveButton(ResStringUtil.getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        generateWallet();
//                    }
//                })
//                .setNegativeButton(R.string.common_text_cancel, null)
//                .create()
//                .show();
//    }
//
////    private void showLogOutAlert() {
////        new AlertDialog.Builder(this)
////                .setTitle(R.string.common_text_hint)
////                .setMessage("用户登录过期，请重新登录")
////                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
////                    @Override
////                    public void onClick(DialogInterface dialogInterface, int i) {
////                        EventBus.getDefault().post(new LogoutEvent());
////                    }
////                })
////                .setCancelable(false)
////                .create().show();
////    }
//
//    private void showSuccessAlert() {
//        new AlertDialog.Builder(CreateWalletConfirm.this)
//                .setTitle(R.string.common_text_hint)
//                .setMessage(ResStringUtil.getString(R.string.openplanet_jidi_create_success))
//                .setPositiveButton(ResStringUtil.getString(R.string.openplanet_goback), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
////                        Intent intent = new Intent(CreateWalletConfirm.this, BackupWalletActivity.class);
//                        Intent intent = new Intent(CreateWalletConfirm.this, BackupTokenHelperActivity.class);
//
//                        intent.putExtra("userName", userName);
//                        intent.putExtra("number", number);
//                        intent.putExtra("mnemonic", mnemonic);//助记词
//                        intent.putExtra("address", address);
//
//                        intent.putExtra("ethPublicKey", ecKeyPair.getPublicKey().toString());
//                        intent.putExtra(CreateWalletActivity.LAST_ACTIVITY, getIntent().getStringExtra(CreateWalletActivity.LAST_ACTIVITY));
//                        startActivity(intent);
//                    }
//                })
//                .create().show();
//    }
//
//
//}